package android.tusnotas.model;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.tusnotas.beans.News;

public class NewsModel {
	
//INSERTS
	public long insertNews(String content, Integer courseId) {
		TusNotasModel.newsInsertStmt.bindString(1, content);
		TusNotasModel.newsInsertStmt.bindDouble(2, courseId);
		return TusNotasModel.newsInsertStmt.executeInsert();
	}
		
	public long insertNews(News news) {
		TusNotasModel.newsInsertStmt.bindString(1, news.getContent());
		TusNotasModel.newsInsertStmt.bindDouble(2, news.getCourseId());
		try{
			return TusNotasModel.newsInsertStmt.executeInsert();
		}catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
//END INSERTS
		
		
//UPDATES	
	public int updateNews(Integer id, String content) {
		ContentValues contentValues = new ContentValues();
		contentValues.put("content", content);
		return TusNotasModel.db.update(TusNotasModel.NEWS_TABLE_NAME, contentValues, "id = ?" , new String[]{id.toString()});
	}
			
	public int updateNews(News news) {
		ContentValues contentValues = new ContentValues();
		contentValues.put("content", news.getContent());
		return TusNotasModel.db.update(TusNotasModel.NEWS_TABLE_NAME, contentValues, "id = ?" , new String[]{news.getId().toString()});
	}
//END UPDATES
			
	
//DELETES
	public void deleteAllNews() {
		TusNotasModel.db.delete(TusNotasModel.NEWS_TABLE_NAME, null, null);
	}
	
	public void deleteNewsById(Integer id) {
		TusNotasModel.db.delete(TusNotasModel.NEWS_TABLE_NAME, "id = "+id, null);
	}
//END DELETES	
	
	
//SELECTS
	public List<News> selectAllNews(){
		List<News> news = new ArrayList<News>();
		News newsAux = null;
		Cursor cursor = TusNotasModel.db.query(TusNotasModel.NEWS_TABLE_NAME, new String[] { "id", "content", "courseId" },
				null, null, null, null, "id ASC");
		
		if (cursor.moveToFirst()) {
			do {
				newsAux = new News();
				newsAux.setId(cursor.getInt(0));
				newsAux.setContent(cursor.getString(1));
				newsAux.setCourseId(cursor.getInt(3)); // o 2
				news.add(newsAux);
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return news;
	}
	
	public List<News> selectNewsByCourse(Integer courseId) {
		List<News> news = new ArrayList<News>();
		News newsAux = null;
		Cursor cursor = TusNotasModel.db.query(TusNotasModel.NEWS_TABLE_NAME, new String[] { "id", "content", "courseId" },
				"courseId ='"+ courseId +"'", null, null, null, "id ASC");
		
		if (cursor.moveToFirst()) {
			do {
				newsAux = new News();
				newsAux.setId(cursor.getInt(0));
				newsAux.setContent(cursor.getString(1));
				newsAux.setCourseId(cursor.getInt(2));
				news.add(newsAux);
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return news;
	}
		
//END SELECTS

}